package com.company.socket.nio文件实例;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Classname FastCopy
 * @Description TODO
 * @Date 2021/8/7 12:12
 * @Created by ylr
 */
public class FastCopy {
    public static void copy(String src,String dist){
        try {
            /*获得源文件输入字节流*/
            FileInputStream fileInputStream = new FileInputStream(src);
            /*获得输入字节流文件通道*/
            FileChannel inputStreamChannel = fileInputStream.getChannel();

            /*目标输出字节流*/
            FileOutputStream fileOutputStream = new FileOutputStream(dist);
            /*获得输出字节流通道*/
            FileChannel outputStreamChannel = fileOutputStream.getChannel();

            /* 缓存区分配1024个字节*/
            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);
            while (true){
                /*输入通道中读取数据到缓存区*/
                int read = inputStreamChannel.read(byteBuffer);

                /* read 返回-1表示EOF*/
                if (read == -1){
                    break;
                }
                /*切换读写*/
                byteBuffer.flip();

                /*把缓存区的内容写入输出文件*/
                outputStreamChannel.write(byteBuffer);

                /*清空缓存区*/
                byteBuffer.clear();


            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
